package com.yuanye.gwcit.fragments;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.yuanye.gwcit.GW;
import com.yuanye.gwcit.PcbaActivity;
import com.yuanye.gwcit.R;
import com.yuanye.gwcit.utils.Recorder;
import com.yuanye.yeecho.base.BaseFragment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class HeadsetRecorderFragment extends BaseFragment {

    String TAG = HeadsetRecorderFragment.class.getSimpleName();

    TextView tvTips, tvMaxValue;
    Button btnPass, btnFail ,btnTest;
    ProgressBar progressBar;
    Recorder recorder;
    Handler handler;
    int max_value = 0;
    int RECORD_DURATION;
    String recorderFileName = "/sdcard/recorder.3gp";
    private AudioManager audioManager;
    private HeadphoneReceiver headphoneReceiver;
    private MediaPlayer mediaPlayer;

    public HeadsetRecorderFragment() {
        setTaskName("耳麦");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_headset_recorder, container, false);
        tvTips = view.findViewById(R.id.tvTips);
        tvMaxValue = view.findViewById(R.id.tvMaxValue);
        progressBar = view.findViewById(R.id.progressBar);
        progressBar.setMax(10000);
        recorder = new Recorder();
        handler = new Handler(Looper.getMainLooper());

        audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        return view;
    }

    @Override
    public void execTask() {
        lock();
        try {
            RECORD_DURATION = Integer.parseInt(GW.cfgPcba.getRecordTime());
            if (RECORD_DURATION < 3){
                RECORD_DURATION = 3;
            }else if (RECORD_DURATION > 10){
                RECORD_DURATION = 10;
            }
        }catch (NumberFormatException e){
            RECORD_DURATION = 5;
        }
        boolean flag = audioManager.isWiredHeadsetOn();
        Log.d(TAG, "耳机是否插入:"+flag);
        if (flag){
            tvTips.setText("耳机已连接, 开始录音..(剩余"+RECORD_DURATION+"秒)");
            recorder.startRecording(recorderFileName);
            handler.post(updateAmplitudeTask);
            CountDownTimer countDownTimer = new CountDownTimer(RECORD_DURATION*1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    tvTips.setText("正在录音..(剩余"+RECORD_DURATION+"秒)");
                    RECORD_DURATION--;
                }

                @Override
                public void onFinish() {
                    tvTips.setText("录音结束");
                    recorder.stopRecording();
                    handler.removeCallbacks(updateAmplitudeTask);
                    checkRecorder();
                }
            };
            countDownTimer.start();
        }else{
            tvTips.setText("请插入耳机");
            //注册广播
            IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
            if (headphoneReceiver == null){
                headphoneReceiver = new HeadphoneReceiver();
                getContext().registerReceiver(headphoneReceiver, filter);
            }
        }
    }

    private void checkRecorder() {
        if (max_value < 1500){
            tvTips.setText("录入音量不够，请重新测试");
            unlock();
            return;
        }
        playWav(new File(recorderFileName));
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
                .setMessage("录音是否完整清晰？")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tvTips.setText("判定通过");
                        passAndNext();
                    }
                })
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tvTips.setText("判定失败");
                        setFail();
                    }
                })
                .setCancelable(false);
        builder.show();
    }

    @Override
    public void stopTask() {
        unlock();
        if (headphoneReceiver != null) {
            getContext().unregisterReceiver(headphoneReceiver);
            headphoneReceiver = null;
        }
        //停止播放录音
        stopPlayWav();
        //删除录音临时文件
        deleteRecordFile(recorderFileName);
    }

    private Runnable updateAmplitudeTask = new Runnable() {
        @Override
        public void run() {
            int amplitude = recorder.getAmplitude();
            Log.d(TAG, ""+amplitude);
            if (amplitude > max_value){
                max_value = amplitude;
            }
            tvMaxValue.setText(""+amplitude);
            progressBar.setProgress(amplitude);
            handler.postDelayed(this, 100);
        }
    };

    private void playWav(File file){
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setVolume(1.0f, 1.0f);
        mediaPlayer.setLooping(true);
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
            }
        });
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                Log.d(TAG, "播放完了");
            }
        });
        try {
            FileInputStream fis = new FileInputStream(file);
            mediaPlayer.setDataSource(fis.getFD());
            mediaPlayer.prepare();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopPlayWav(){
        if (mediaPlayer!=null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void deleteRecordFile(String recorderFileName){
        File file = new File(recorderFileName);
        if (file.exists()){
            file.delete();
        }
    }

    class HeadphoneReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                int state = intent.getIntExtra("state", -1);
                if (state == 0) {
                    // 耳机拔出
//                    Toast.makeText(context, "请插入耳机", Toast.LENGTH_SHORT).show();

                } else if (state == 1) {
                    // 耳机插入
//                    Toast.makeText(context, "耳机已连接", Toast.LENGTH_SHORT).show();
                    execTask();
                }
            }
        }
    }

}
